//#include "StdAfx.h"
#include "base_thread.h"

base_thread::base_thread(void)
{
	m_hThread    = NULL;
	m_dwThreadID = 0;
	m_hEvent = CreateEvent( NULL, TRUE, FALSE, NULL );
}

base_thread::~base_thread(void)
{
	if( m_hEvent != NULL )
	{
		CloseHandle( m_hEvent );
		m_hEvent = NULL;
	}
	TerminateThread( -1 );
}
bool base_thread::CreateThread( void * psa, unsigned cbStatck, PTHREAD_START pfn, void * param, unsigned fdwCreate )
{
//	m_param.m_arg = param;
	ResetEvent( m_hEvent );
	m_hThread = chBEGINTHREADEX( psa, cbStatck, pfn, param, fdwCreate, &m_dwThreadID );
	if( m_hThread == NULL )
		return false;
	return true;
}
bool base_thread::IsTheadStop( int nTime /*=1000*/ )
{
	DWORD dwRet = WaitForSingleObject( m_hEvent, nTime );
	if( dwRet == WAIT_OBJECT_0 || dwRet == WAIT_ABANDONED || dwRet == WAIT_FAILED )
		return true;
	else
		return false;
}

void base_thread::ExitThead( int nExitCode )
{
	::ExitThread( nExitCode );
	SetEvent( m_hEvent );
}
bool base_thread::TerminateThread( int nExitCode )
{
	if( m_hThread != NULL )
	{
		if( ::TerminateThread( m_hThread, nExitCode )==TRUE )
		{
			SetEvent( m_hEvent );
			return true;
		}
		else
			return false;
	}
	else
		return true;
}

void base_thread::StopThread( bool bAsyn )
{
	SetEvent( m_hEvent );
	if( m_hThread != NULL )
	{
		if( !bAsyn )
			WaitForSingleObject( m_hThread, INFINITE );
		CloseHandle( m_hThread );
    	m_hThread = NULL;
	}
}
int  base_thread::GetExitCode()
{
	DWORD dwRetCode = 0;
	::GetExitCodeThread( m_hThread, &dwRetCode );
	return dwRetCode;
}